// import { useCallback, useEffect } from 'react';
import BackPage from '@/components/BackPage';
import ManageBadge from '@/components/ManageBadge';
import SaleBadge from '@/components/SaleBadge';
import { getBar, getOrderCount } from '@/services/orders';
import { getLine } from '@/services/payouts';
import { getCount } from '@/services/user';
import { getQueryParams } from '@/utils/utils';
import { Col, Empty, Row, Select, Statistic } from 'antd';
import EchartsBar from 'echarts-for-react';
import React, { useCallback, useEffect, useState } from 'react';
import { monthList } from './constants';
import styles from './index.less';

const HomePage: React.FC = () => {
  const qs = getQueryParams();
  let now = new Date().getTime();
  let howLong = ((now - qs.timeadd) / (1000 * 60 * 60 * 24)).toFixed(0);
  const [lineName, setLineName] = useState<any[]>([]);
  const [annual, setAnnual] = useState<string>('2023');
  const [saleDate, setSaleDate] = useState<any[]>([]);
  const [buyDate, setBuyDate] = useState<any[]>([]);
  const [adsDate, setAdsDate] = useState<any[]>([]);
  const [countDate, setCountDate] = useState<any[]>([]);
  const [barDate, setBarDate] = useState<any[]>([]);
  const [barDateTwo, setBarDateTwo] = useState<any[]>([]);
  const [saleMoney, setSaleMoney] = useState<number>(0);
  const [ifHavaDate, setIfHavaDate] = useState<boolean>(true);

  const getLineDate = useCallback(
    async (start: any, end: any) => {
      qs.role === '3'
        ? await getLine({ start: start, end: end }).then((res) => {
            if (JSON.stringify(res) === JSON.stringify({})) {
              setIfHavaDate(false);
            } else {
              setIfHavaDate(true);
              setLineName(res.xAxis);
              res.series.map((item: any) => {
                if (item.name === '1') {
                  setSaleDate(item.moneyArray);
                }
                if (item.name === '2') {
                  setBuyDate(item.moneyArray);
                } else {
                  setAdsDate(item.moneyArray);
                }
              });
            }
          })
        : await getBar({ start: start, end: end, userId: qs.id }).then((res) => {
            if (JSON.stringify(res) === JSON.stringify({})) {
              setIfHavaDate(false);
            } else {
              setIfHavaDate(true);
              setLineName(res.xAxis);
              res.series.map((item: any) => {
                let moneyCurr = 0;
                if (item.name === '5') {
                  setBarDate(item.moneyArray);
                  let arr: any = [];
                  item.moneyArray.map((itemMoney: any) => {
                    moneyCurr = moneyCurr + itemMoney;
                    arr.push(itemMoney * 0.8);
                  });
                  setBarDateTwo(arr);
                  setSaleMoney(moneyCurr);
                }
              });
            }
          });
    },
    [qs.id, qs.role],
  );

  const yearChange = (e: any) => {
    setAnnual(e);
  };

  const getCountDate = useCallback(async () => {
    if (qs.role === '3') {
      await getCount({}).then((res) => {
        setCountDate(res);
      });
    } else {
      await getOrderCount({ userId: qs.id }).then((res) => {
        setCountDate(res);
      });
    }
  }, [qs.id, qs.role]);

  useEffect(() => {
    switch (annual) {
      case '2023':
        getLineDate('1672502400000', '1704038399999');
        break;
      case '2022':
        getLineDate('1640966400000', '1672502399999');
        break;
      case '2021':
        getLineDate('1609430400000', '1640966399999');
        break;
      case '2020':
        getLineDate('1577808000000', '1609430399999');
        break;
      default:
        break;
    }
  }, [annual, getLineDate]);

  useEffect(() => {
    getCountDate();
  }, [getCountDate]);

  const optionTwo = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      data: ['营业额', '已到账'],
    },
    color: ['#748BFF', '#DFE6FF', '#A776FF'],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data:
          lineName === undefined
            ? monthList.map((item) => {
                return `${annual}-${item}`;
              })
            : lineName.map((item) => {
                return `${annual}-${item}`;
              }),
      },
    ],
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          formatter: '￥{value}',
        },
      },
    ],
    series: [
      {
        name: '营业额',
        type: 'bar',
        stack: 'Ad',
        emphasis: {
          focus: 'series',
        },
        itemStyle: {
          barBorderRadius: 4,
        },
        data: barDate,
      },
      {
        name: '已到账',
        type: 'bar',
        emphasis: {
          focus: 'series',
        },
        data: barDateTwo,
      },
    ],
  };

  const optionThree = {
    title: {
      text: '',
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['商家抽成', '买家充值', '广告投放'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    toolbox: {
      feature: {
        saveAsImage: {
          title: '以.png格式保存',
        },
      },
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data:
        lineName === undefined
          ? monthList.map((item) => {
              return `${annual}-${item}`;
            })
          : lineName.map((item) => {
              return `${annual}-${item}`;
            }),
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '￥{value}',
      },
    },
    series: [
      {
        name: '商家抽成',
        type: 'line',
        data: saleDate,
      },
      {
        name: '',
        type: 'line',
        data: [],
      },
      {
        name: '买家充值',
        type: 'line',
        data: buyDate,
      },
      {
        name: '广告投放',
        type: 'line',
        data: adsDate,
      },
    ],
  };

  return (
    <BackPage thisRoute={'/back'} lastRoute={'数据浏览'}>
      {ifHavaDate ? (
        qs.role === '2' ? (
          <div className={styles.twoContainer}>
            <div className={styles.topText}>您的店铺已经营业：{howLong} 天啦！</div>
            <div className={styles.dataSee}>
              <Row gutter={16}>
                <Col span={12}>
                  <Statistic
                    title="已完成的订单数"
                    value={countDate[1]}
                    suffix={`/${countDate[0]}`}
                  />
                </Col>
                <Col span={12}>
                  <Statistic title={`${annual}年您已经赚取了`} value={saleMoney} precision={2} />
                </Col>
              </Row>
            </div>
            <div className={styles.echart}>
              <div className={styles.echartText}>
                {`您`}&nbsp;
                <Select
                  defaultValue="2023"
                  style={{ width: 120 }}
                  onChange={yearChange}
                  options={[
                    { value: '2023', label: '2023' },
                    { value: '2022', label: '2022' },
                    { value: '2021', label: '2021' },
                    { value: '2020', label: '2020' },
                  ]}
                >
                  <Select.Option key={'2023'} value="2023">
                    2023
                  </Select.Option>
                  {1640966400000 < qs.timeadd && (
                    <Select.Option key={'2022'} value="2022">
                      2022
                    </Select.Option>
                  )}
                  {1609430400000 < qs.timeadd && (
                    <Select.Option key={'2021'} value="2021">
                      2021
                    </Select.Option>
                  )}
                  {1577808000000 < qs.timeadd && (
                    <Select.Option key={'2020'} value="2020">
                      2020
                    </Select.Option>
                  )}
                </Select>
                &nbsp;
                {`年营业额如下：`}
              </div>
              <EchartsBar option={optionTwo} />
            </div>
            <SaleBadge />
          </div>
        ) : (
          <div className={styles.threeContainer}>
            <div className={styles.topText}>欢迎回来！{qs.nickname}</div>
            <div className={styles.dataSee}>
              <Row gutter={16}>
                <Col span={12}>
                  <Statistic title="买家总数" value={countDate[0]} />
                </Col>
                <Col span={12}>
                  <Statistic title="商家总数" value={countDate[1]} />
                </Col>
              </Row>
            </div>
            <div className={styles.echart}>
              <div className={styles.echartText}>
                <Select
                  style={{ width: 120 }}
                  value={annual}
                  onChange={yearChange}
                  options={[
                    { value: '2023', label: '2023' },
                    { value: '2022', label: '2022' },
                    { value: '2021', label: '2021' },
                    { value: '2020', label: '2020' },
                  ]}
                />
                &nbsp;
                {`年网站进项如下：`}
              </div>
              <EchartsBar option={optionThree} />
            </div>
            <ManageBadge />
          </div>
        )
      ) : (
        <div className={styles.emptyDiv}>
          {qs.role === '2' ? (
            <div className={styles.emptyTextTitle}>
              {`您`}&nbsp;
              <Select
                value={annual}
                style={{ width: 120 }}
                onChange={yearChange}
                options={[
                  { value: '2023', label: '2023' },
                  { value: '2022', label: '2022' },
                  { value: '2021', label: '2021' },
                  { value: '2020', label: '2020' },
                ]}
              >
                <Select.Option key={'2023'} value="2023">
                  2023
                </Select.Option>
                {1640966400000 < qs.timeadd && (
                  <Select.Option key={'2022'} value="2022">
                    2022
                  </Select.Option>
                )}
                {1609430400000 < qs.timeadd && (
                  <Select.Option key={'2021'} value="2021">
                    2021
                  </Select.Option>
                )}
                {1577808000000 < qs.timeadd && (
                  <Select.Option key={'2020'} value="2020">
                    2020
                  </Select.Option>
                )}
              </Select>
              &nbsp;
              {`年营业额如下：`}
            </div>
          ) : (
            <div className={styles.emptyTextTitle}>
              <Select
                defaultValue="2023"
                style={{ width: 120 }}
                onChange={yearChange}
                options={[
                  { value: '2023', label: '2023' },
                  { value: '2022', label: '2022' },
                  { value: '2021', label: '2021' },
                  { value: '2020', label: '2020' },
                ]}
              />
              &nbsp;
              {`年网站进项如下：`}
            </div>
          )}
          <Empty
            image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
            imageStyle={{ height: 60 }}
            description={<span />}
          >
            <div className={styles.emptyText}>
              {`您${annual}年暂无${qs.role === '2' ? '营业额' : '进项'}`}
            </div>
          </Empty>
          {qs.role === '2' ? <SaleBadge /> : <ManageBadge />}
        </div>
      )}
    </BackPage>
  );
};
export default HomePage;
